package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyMsgHandler implements MsgHandler {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        assert supplyContract!=null&&supplyContract.getSupplyData().size()!=0;
        //創建工單
        supplyContract.getSupplyData().forEach(
                supplyChannel -> {
                    createTask(supplyChannel,supplyContract.getInnerCode() );
                }
        );
    }

    /**
     * 創建工單
     * @param supplyChannel
     */
    private void createTask(SupplyChannel supplyChannel ,String innerCode) {
        TaskViewModel taskViewModel = new TaskViewModel();
        TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
        BeanUtils.copyProperties(supplyChannel,taskDetailsViewModel);
        taskDetailsViewModel.setChannelCode(supplyChannel.getChannelId());
        taskDetailsViewModel.setExpectCapacity(supplyChannel.getCapacity());
        taskViewModel.setCreateType(0);
        taskViewModel.setInnerCode(innerCode);
        taskViewModel.setAssignorId(1);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        //獲取運營人員id
        Integer userId = getUserId(innerCode);
        taskViewModel.setUserId(userId);
        taskService.add(taskViewModel);
    }

    /**
     * 獲取運營人員Id
     * @param innerCode
     * @return
     */
    private Integer getUserId(String innerCode) {
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        String date = LocalDate.now().plusDays(0).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd-user-service-redis"+date+vmInfo.getRegionId()+VMSystem.USER_OPERATOR;
        Set<Integer> range = redisTemplate.opsForZSet().range(key, 0, 1);
         return range.stream().collect(Collectors.toList()).get(0);
    }
}
